const connection = require('../app/database')
class CommentService {
    async create(momentId, content, userId) {
        const statement = `INSERT INTO comment (content,moment_id,user_id)
        VALUES(?,?,?);`
        const [result] = await connection.execute(statement, [content, momentId, userId])

        return result
    }
    async reply(momentId, content, userId, commentId) {

        const statement = `INSERT INTO comment (content,moment_id,user_id,comment_id)
        VALUES(?,?,?,?);`
        const [result] = await connection.execute(statement, [content, momentId, userId, commentId])

        return result
    }
    async replycomment(content, momentId, commentId,
        reply_comment_id, target_user_name, userId) {

        const statement = `INSERT INTO comment (content,moment_id,comment_id,
                            reply_comment_id, target_user_name,user_id)
                            VALUES(?,?,?,?,?,?);`
        const [result] = await connection.execute(statement, [content, momentId, commentId,
            reply_comment_id, target_user_name, userId])

        return result
    }
    async update(commentId, content) {
        const statement = `UPDATE comment SET content = ? WHERE id = ?;`
        const [result] = await connection.execute(statement, [content, commentId])

        return result
    }
    async getCommentByMomentId(momentId) {
        const statement = `			SELECT c.id,c.content,c.moment_id,c.comment_id,c.user_id,u.name user_name,u.avatar_url,c.target_user_id,c.target_user_name,

				(SELECT JSON_ARRAYAGG(JSON_OBJECT('id',ct.id,'content',ct.content,'moment_id',ct.comment_id,
        'user_id',ct.user_id,'user_name',u.name,'avatar_url',u.avatar_url,'comment_id',ct.comment_id,'target_user_id',ct.target_user_id,						'target_user_name',ct.target_user_name,'reply_comment_id',ct.reply_comment_id))
        FROM comment ct
        LEFT JOIN users u ON ct.user_id = u.id

        WHERE c.id=ct.comment_id) children

        FROM comment c
				LEFT JOIN users u ON c.user_id = u.id
        WHERE c.comment_id IS NULL AND c.moment_id = ?;`
        const [result] = await connection.execute(statement, [momentId])

        return result
    }
}
module.exports = new CommentService()